package com.mages.dataService.service;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
public class GeoService {

    private static String physicalIP;

    @Value("${PHYSICAL_IP:192.168.101.101}")
    public void setPhysicalIP(String physicalIP) {
        GeoService.physicalIP = physicalIP;
    }


    public void delete(String url,String deleteUrl){

        String user = "admin";
        String password = "geoserver";
        System.out.println("Geo_physicalIP: " + physicalIP);

        try (CloseableHttpClient client = HttpClients.createDefault()) {

            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("accept", "application/xml");

            String auth = Base64.getEncoder().encodeToString(String.format("%s:%s", user, password).getBytes(StandardCharsets.UTF_8));
            httpGet.addHeader("Authorization", String.format("Basic %s", auth));

            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                String xmlResponse = EntityUtils.toString(entity);
                // Parse the XML response to get the file list
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.parse(new InputSource(new StringReader(xmlResponse)));
                NodeList coverageNodes = doc.getElementsByTagName("name");

                // Iterate through the coverage nodes and delete files
                for (int i = 0; i < coverageNodes.getLength(); i++) {
                    Node coverageNode = coverageNodes.item(i);
                    String coverageName = coverageNode.getTextContent();

                    if (!coverageName.equals("dem") && !coverageName.equals("dom") && !coverageName.equals("dsm") && !coverageName.equals("2019HyperSpectral")) {
                        // Delete files that are not "dem," "dom," or "dsm"

                        String deleteUrl_new = deleteUrl.replace("coverageName", coverageName);

                        HttpDelete httpDelete = new HttpDelete(deleteUrl_new);
                        httpDelete.addHeader("Authorization",String.format("Basic %s", auth));
                        httpDelete.addHeader("accept", "application/json");
                        httpDelete.addHeader("content-type", "application/json");
                        HttpResponse deleteResponse = client.execute(httpDelete);

                        if (deleteResponse.getStatusLine().getStatusCode() == 200) {
                            System.out.println("Deleted coverage: " + coverageName);
                        } else {
                            System.out.println("Failed to delete coverage: " + coverageName);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    @Scheduled(cron="0/10 * *  * * ? ")
    @Scheduled(cron="0 0 0 */1 * ?")//每1天执行一次
    public void execute(){
        String GeoServerIP = physicalIP+":8080";
        String url1 = "http://"+GeoServerIP+"/geoserver/rest/workspaces/service_chain/layers";
        String url2 = "http://"+GeoServerIP+"/geoserver/rest/workspaces/service_chain/coverages";
        String url3 = "http://"+GeoServerIP+"/geoserver/rest/workspaces/service_chain/coveragestores";

        String deleteUrl1 = "http://"+GeoServerIP+"/geoserver/rest/workspaces/service_chain/layers/coverageName";
        String deleteUrl2 = "http://"+GeoServerIP+"/geoserver/rest/workspaces/service_chain/coveragestores/coverageName/coverages/coverageName?purge=all";
        String deleteUrl3 = "http://"+GeoServerIP+"/geoserver/rest/workspaces/service_chain/coveragestores/coverageName";

        String[] urls = {url1, url2, url3};
        String[] deleteUrls = {deleteUrl1, deleteUrl2, deleteUrl3};
        for (int i = 0; i < urls.length; i++) {
            String url = urls[i];
            String deleteUrl = deleteUrls[i];
            delete(url,deleteUrl);
        }


    }
}
